<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\common\logic;

use think\Db;

/**
 * 消息通知业务层
 */
load_trait('controller/Jump');
class NoticeLogic 
{
    use \traits\controller\Jump;
    public function __construct() 
    {
        // 设置内置内容数据
        $this->setBuiltInArray();

        // 获取内置内容数组
        $this->builtInArray = $this->getBuiltInArray();
    }

    // 获取微信公众号消息通知发送内容
    public function getSendWeChatContent($users = [], $content = [], $sendScene = [])
    {
        // 是否传入用户信息、发送内容、发送类型，缺一则返回结束
        if (empty($users) || empty($content) || empty($sendScene)) return false;

        $where = [
            'send_scene' => ['IN', $sendScene]
        ];
        $weChatList = Db::name('wechat_template')->where($where)->select();
        foreach ($weChatList as $key => $value) {
            // 如果关闭推送开关则跳过
            if (empty($value['is_open'])) {
                unset($value);
                unset($weChatList[$key]);
                continue;
            }

            // 买家通知
            if (in_array($value['send_scene'], [30, 31, 32, 33, 34, 35])) {
                if (!empty($users['open_id'])) {
                    $value['open_id'] = trim($users['open_id']);
                } else {
                    unset($value);
                    unset($weChatList[$key]);
                    continue;
                }
            }
            // 卖家通知
            else if (in_array($value['send_scene'], [50, 51, 52, 53])) {
                $value['open_id'] = '';
            }

            $weChatList[$key] = $value;
        }

        if (!empty($weChatList)) {
            $sendContent = [
                'weChat' => $weChatList,
                'content' => $content,
            ];
            $resultID = $this->addNoticeSendContent($sendContent, $content, 1, $sendScene);
            if (!empty($resultID)) return intval($resultID);
        }
        return false;
    }

    // 执行微信公众号消息通知发送内容
    public function executeSendWeChatContent($send_id = '', $return = true)
    {
        // 获取通知发送记录表信息
        $noticeList = $this->getNoticeSendContent($send_id, 1);
        if (empty($noticeList)) $this->success('没有推送消息');

        // 查询需要推送的管理员
        $where = [
            'admin_id' => ['IN', [4, 5]], // 此条件测试完成上线时去掉
            'wechat_followed' => 1,
            'wechat_open_id' => ['NEQ', '']
        ];
        $adminList = Db::name('admin')->where($where)->column('wechat_open_id');

        // 获取微信公众号 access_token
        $tokenData = get_wechat_access_token();
        foreach ($noticeList as $noticeSend) {
            if (!empty($noticeSend['send_content']['weChat']) && !empty($noticeSend['send_content']['content'])) {
                // 推送内容
                $content = $noticeSend['send_content']['content'];
                $weChatList = $noticeSend['send_content']['weChat'];

                // 处理推送消息
                foreach ($weChatList as $value) {
                    if (!empty($value['is_open']) && !empty($content) && !empty($tokenData['code'])) {
                        $url = '';
                        // 买家通知
                        if (in_array($value['send_scene'], [30, 31, 32, 33, 34, 35]) && !empty($value['open_id'])) {
                            // 获取微信公众号消息通知发送模板
                            $data = $this->getWeChatTemplateContent($value, $content);
                            // 售后订单
                            if (32 === intval($value['send_scene']) && !empty($content['service_id'])) {
                                $url = request()->domain() . ROOT_DIR . '/h5/#/otherpages/mall/order/service/detail?service_id=' . $content['service_id'];
                            }
                            // 会员充值
                            else if (33 === intval($value['send_scene']) && !empty($content['moneyid'])) {
                                $url = request()->domain() . ROOT_DIR . '/h5/#/otherpages/user/wallet/withdrawal/record';
                            }
                            // 商城订单
                            else if (!empty($content['order_id'])) {
                                $url = request()->domain() . ROOT_DIR . '/h5/#/otherpages/mall/order/detail?order_id=' . $content['order_id'];
                            }
                            // 执行调用微信公众号消息通知接口
                            $this->executeCallWeChatPort($data, $value['open_id'], $value['template_id'], $url, $tokenData['access_token']);
                        }
                        // 卖家通知
                        else if (in_array($value['send_scene'], [50, 51, 52, 53]) && !empty($adminList)) {
                            foreach ($adminList as $open_key => $open_id) {
                                if (!empty($open_id)) {
                                    // 获取微信公众号消息通知发送模板
                                    $data = $this->getWeChatTemplateContent($value, $content);
                                    // 售后订单
                                    if (52 === intval($value['send_scene']) && !empty($content['service_id'])) {
                                        $url = weapp_url('Mbackend/Shop/after_service_details', ['service_id'=>$content['service_id'], 'isMobile'=>1], true, true);
                                    }
                                    // 商城订单
                                    else if (!empty($content['order_id'])) {
                                        $url = weapp_url('Mbackend/Shop/order_details', ['order_id'=>$content['order_id'], 'isMobile'=>1], true, true);
                                    }
                                    // URL处理成后台访问路径
                                    $url = str_replace('m=api', 'm=admin', $url);
                                    $url = str_replace('m=home', 'm=admin', $url);
                                    $url = str_replace('index.php', 'login.php', $url);
                                    // 执行调用微信公众号消息通知接口
                                    $this->executeCallWeChatPort($data, $open_id, $value['template_id'], $url, $tokenData['access_token']);
                                }
                            }
                        }
                    }
                }
            }
        }

        // 更新通知发送记录表信息
        $this->updateNoticeSendContent($send_id, 1);

        // 返回结束
        if (!empty($return)) $this->success('推送成功');
    }

    // 获取微信公众号消息通知发送模板
    public function getWeChatTemplateContent($value = [], $content = [])
    {
        // 买家通知 --- 订单付款
        if (30 === intval($value['send_scene'])) {
            $content['goodsTitle'] = !empty($content['goodsTitle']) ? $content['goodsTitle'] : Db::name('shop_order_details')->where(['order_id'=>$content['order_id']])->order('details_id desc')->getField('product_name');
            $content['goodsTitleNew'] = msubstr($content['goodsTitle'], 0, 17);
            if (trim($content['goodsTitle']) !== trim($content['goodsTitleNew'])) $content['goodsTitleNew'] .= '...';
            $data = [
                'character_string1' => [
                    'value' => $content['order_code'],
                ],
                'thing4' => [
                    'value' => $content['goodsTitleNew'],
                ],
                'time2' => [
                    'value' => MyDate('Y-m-d H:i:s', $content['pay_time']),
                ],
                'amount3' => [
                    'value' => "{$content['order_amount']}元",
                ],
            ];
        }
        // 买家通知 --- 订单发货
        else if (31 === intval($value['send_scene'])) {
            $content['addressNew'] = msubstr($content['address'], 0, 17);
            if (trim($content['address']) !== trim($content['addressNew'])) $content['addressNew'] .= '...';
            $data = [
                'character_string2' => [
                    'value' => $content['order_code'],
                ],
                'time3' => [
                    'value' => MyDate('Y-m-d H:i:s', $content['express_time']),
                ],
                'thing5' => [
                    'value' => $content['express_name'],
                ],
                'character_string11' => [
                    'value' => $content['express_order'],
                ],
                'thing12' => [
                    'value' => $content['addressNew'],
                ],
            ];
        }
        // 买家通知 --- 订单退款
        else if (32 === intval($value['send_scene'])) {
            $content['product_nameNew'] = msubstr($content['product_name'], 0, 17);
            if (trim($content['product_name']) !== trim($content['product_nameNew'])) $content['product_nameNew'] .= '...';
            $data = [
                'amount2' => [
                    'value' => "{$content['actual_price']}元",
                ],
                'thing5' => [
                    'value' => $content['product_nameNew'],
                ],
                'character_string1' => [
                    'value' => $content['order_code'],
                ]
            ];
        }
        // 买家通知 --- 充值成功
        else if (33 === intval($value['send_scene'])) {
            $data = [
                'thing3' => [
                    'value' => $content['nickname'],
                ],
                'amount5' => [
                    'value' => $content['money'],
                ],
                'amount6' => [
                    'value' => $content['users_money'],
                ],
                'time11' => [
                    'value' => MyDate('Y-m-d H:i:s', $content['add_time']),
                ]
            ];
        }
        // 卖家通知 --- 订单付款
        else if (50 === intval($value['send_scene'])) {
            $data = [
                'amount3' => [
                    'value' => "{$content['order_amount']}元",
                ],
                'character_string1' => [
                    'value' => $content['order_code'],
                ],
            ];
        }
        // 卖家通知 --- 确认收货
        else if (51 === intval($value['send_scene'])) {
            $data = [
                'thing5' => [
                    'value' => $content['consignee'],
                ],
                'character_string1' => [
                    'value' => $content['order_code'],
                ],
                'time8' => [
                    'value' => MyDate('Y-m-d H:i:s', $content['add_time']),
                ],
                'amount3' => [
                    'value' => "{$content['order_amount']}元",
                ],
            ];
        }
        // 卖家通知 --- 订单维权
        else if (52 === intval($value['send_scene'])) {
            $content['product_nameNew'] = msubstr($content['product_name'], 0, 17);
            if (trim($content['product_name']) !== trim($content['product_nameNew'])) $content['product_nameNew'] .= '...';
            $data = [
                'phrase11' => [
                    'value' => $content['service_type_text'],
                ],
                'time15' => [
                    'value' => MyDate('Y-m-d H:i:s', $content['add_time']),
                ],
                'amount20' => [
                    'value' => "{$content['refund_price']}元",
                ],
                'thing17' => [
                    'value' => $content['product_nameNew'],
                ],
                'character_string9' => [
                    'value' => $content['order_code'],
                ],
            ];
        }

        return $data;
    }

    // 执行调用微信公众号消息通知接口
    public function executeCallWeChatPort($data = [], $touser = '', $template_id = '', $url = '', $access_token = '')
    {
        $postData = [
            'data' => $data,
            'touser' => $touser,
            'template_id' => $template_id,
            'client_msg_id' => md5(json_encode($data)),
        ];
        if (!empty($url)) $postData['url'] = $url;
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        httpRequest($url, 'POST', json_encode($postData, JSON_UNESCAPED_UNICODE));
    }

    // 获取发送邮箱内容
    public function getSendEamilContent($users = [], $content = [], $sendScene = [])
    {
        // 如果商品已经推送过预警则跳转不再推送
        // if (!empty($content['goods_id']) && in_array(53, $sendScene)) {
        //     $result = $this->getNoticeSendContent(0, 3, $content['goods_id'], false);
        //     if (!empty($result)) return false;
        // }

        // 【应用】-【消息通知】-【接口配置】-【邮箱配置】
        $config = tpCache('smtp');
        foreach ($config as $value) {
            if (empty($value)) return false;
        }

        // 是否传入用户信息、发送内容、发送类型，缺一则返回结束
        if (empty($users) || empty($content) || empty($sendScene)) return false;

        $where = [
            'send_scene' => ['IN', $sendScene]
        ];
        $emailList = Db::name('smtp_tpl')->where($where)->select();
        foreach ($emailList as $key => $value) {
            // 如果关闭推送开关则跳过
            if (empty($value['is_open'])) {
                unset($value);
                unset($emailList[$key]);
                continue;
            }

            // 买家通知
            if (in_array($value['send_scene'], [30, 31, 32, 33, 34, 35]) && !empty($users['email'])) {
                $value['email'] = trim($users['email']);
            }
            // 卖家通知
            else if (in_array($value['send_scene'], [50, 51, 52, 53]) && !empty($config['smtp_from_eamil'])) {
                $value['email'] = trim($config['smtp_from_eamil']);
            }

            // 如果没有推送邮箱则跳过
            if (empty($value['email'])) {
                unset($value);
                unset($emailList[$key]);
                continue;
            }

            $emailList[$key] = $value;
        }

        if (!empty($emailList)) {
            $sendContent = [
                'email' => $emailList,
                'content' => $content,
            ];
            $resultID = $this->addNoticeSendContent($sendContent, $content, 3, $sendScene);
            if (!empty($resultID)) return intval($resultID);
        }
        return false;
    }

    // 执行邮箱消息通知发送内容
    public function executeSendEamilContent($send_id = '', $return = true)
    {
        $noticeList = $this->getNoticeSendContent($send_id, 3);
        if (empty($noticeList)) $this->success('没有推送消息');

        foreach ($noticeList as $noticeSend) {
            if (!empty($noticeSend['send_content']['email']) && !empty($noticeSend['send_content']['content'])) {
                // 推送内容
                $content = $noticeSend['send_content']['content'];
                $emailList = $noticeSend['send_content']['email'];

                // 处理推送消息
                foreach ($emailList as $value) {
                    if (!empty($value['is_open']) && !empty($content)) {
                        // 买家通知: 30, 31, 32, 33, 34, 35; 卖家通知: 50, 51, 52, 53
                        if (in_array($value['send_scene'], [30, 31, 32, 33, 34, 35, 50, 51, 52, 53]) && !empty($value['email'])) {
                            // 获取邮箱消息通知发送模板
                            $result = $this->getEamilTemplateContent($value, $content);
                            // 执行邮件消息通知接口
                            send_email($value['email'], $result['tpl_title_text'], $result['otherContent'], $value['send_scene']);
                        }
                    }
                }
            }
        }

        // 更新通知发送记录表信息
        $this->updateNoticeSendContent($send_id, 3);

        // 返回结束
        if (!empty($return)) $this->success('推送成功');
    }

    // 获取邮箱消息通知发送模板
    private function getEamilTemplateContent($value = [], $content = [])
    {
        // 加载邮件模板值
        $this->shopName = tpCache('web.web_name');

        // 商城下单
        if (!empty($content['order_id'])) {
            // 积分变动推送
            if (34 === intval($value['send_scene']) && !empty($content['order_points'])) {
                $this->changeType = '减少';
                $this->changeScores = '-' . floatval($content['order_points']);
                $this->changeReason = '积分商品订单支付';
            }
            // 积分变动推送
            else if (34 === intval($value['send_scene']) && !empty($content['obtain_scores'])) {
                $this->changeType = '增加';
                $this->changeScores = '+' . floatval($content['obtain_scores']);
                $this->changeReason = '消费获得积分数';
            }
            // 余额变动推送
            else if (35 === intval($value['send_scene'])) {
                $this->changeType = '减少';
                $this->changeMoney = '-' . floatval($content['order_amount']);
                $this->changeReason = '订单支付成功';
            }
        }
        // 余额充值
        if (35 === intval($value['send_scene']) && !empty($content['moneyid'])) {
            $this->changeType = '增加';
            $this->changeMoney = '+' . floatval($content['money']);
            $this->changeReason = '会员充值成功';
        }

        // 查询客户当前余额
        if (in_array($value['send_scene'], [33, 34, 35]) && !empty($content['users_id'])) {
            $usersInfo = Db::name('users')->field('users_money, scores')->where(['users_id' => intval($content['users_id'])])->find();
            $this->usersMoney = !empty($usersInfo['users_money']) ? floatval($usersInfo['users_money']) : 0;
            $this->usersScores = !empty($usersInfo['scores']) ? intval($usersInfo['scores']) : 0;
        }

        /*if (35 === intval($value['send_scene'])) {
            $this->changeReason = '充值成功';
        } else if (34 === intval($value['send_scene'])) {
            $this->changeReason = '消费获得积分';
        }*/

        if (!empty($content['money'])) $this->money = $content['money'];
        if (!empty($content['address'])) $this->address = $content['address'];
        if (!empty($content['nickname'])) $this->nickname = $content['nickname'];
        if (!empty($content['order_amount'])) $this->money = $content['order_amount'];
        if (!empty($content['refund_price'])) $this->money = $content['refund_price'];
        if (!empty($content['order_code'])) $this->orderCode = $content['order_code'];
        if (!empty($content['goodsStock'])) $this->goodsStock = $content['goodsStock'];
        if (!empty($content['express_name'])) $this->express_name = $content['express_name'];
        if (!empty($content['express_order'])) $this->express_order = $content['express_order'];
        if (!empty($content['actual_price'])) $this->actualPrice = floatval($content['actual_price']);
        if (!empty($content['add_time'])) $this->add_time = date('Y-m-d H:i:s', $content['add_time']);
        if (!empty($content['pay_time'])) $this->pay_time = date('Y-m-d H:i:s', $content['pay_time']);
        if (!empty($content['express_time'])) $this->express_time = date('Y-m-d H:i:s', $content['express_time']);
        if (!empty($content['confirm_time'])) $this->confirm_time = date('Y-m-d H:i:s', $content['confirm_time']);
        // 商品标题处理
        $this->goodsTitle = !empty($content['goodsTitle']) ? $content['goodsTitle'] : '';
        if (empty($this->goodsTitle) && !empty($content['order_id'])) {
            $this->goodsTitle = Db::name('shop_order_details')->where(['order_id'=>$content['order_id']])->order('details_id desc')->getField('product_name');
        }
        $this->builtInArray = $this->getBuiltInArray();

        // 处理邮件模板值
        $result = $this->handleSmtpTemplate($value);
        // 将发送数组转成字符串
        $result['otherContent'] = !empty($result['otherContent']) ? implode('<br/>', $result['otherContent']) : $result['otherContent'];        

        return $result;
    }

    // 处理邮件模板内容
    public function handleSmtpTemplate($info = [])
    {
        // 标题处理
        $info['tpl_title_text'] = str_replace(['${money}','{1}'], $this->money, $info['tpl_title']);
        $info['tpl_title_text'] = str_replace(['${scores}','{1}'], $this->scores, $info['tpl_title_text']);
        $info['tpl_title_text'] = str_replace(['增加或减少','{1}'], $this->changeType, $info['tpl_title_text']);
        $info['tpl_title_text'] = str_replace(['${pay_time}','{1}'], $this->pay_time, $info['tpl_title_text']);
        $info['tpl_title_text'] = str_replace(['${shop_name}','{1}'], $this->shopName, $info['tpl_title_text']);
        $info['tpl_title_text'] = str_replace(['${order_code}','{1}'], $this->orderCode, $info['tpl_title_text']);
        $info['tpl_title_text'] = str_replace(['${goods_title}','{1}'], $this->goodsTitle, $info['tpl_title_text']);
        $info['tpl_title_text'] = str_replace(['${changeMoney}','{1}'], $this->changeMoney, $info['tpl_title_text']);
        $info['tpl_title_text'] = str_replace(['${changeScores}','{1}'], $this->changeScores, $info['tpl_title_text']);
        $info['tpl_title_text'] = str_replace(['${express_time}','{1}'], $this->express_time, $info['tpl_title_text']);
        $info['tpl_title_text'] = str_replace(['${confirm_time}','{1}'], $this->confirm_time, $info['tpl_title_text']);

        // 其他附加内容处理
        $info['otherContent'] = [];
        // 订单支付
        if (30 === intval($info['send_scene'])) {
            $info['otherContent'] = [$this->builtInArray[0], $this->builtInArray[1], $this->builtInArray[11], $this->builtInArray[3]];
        }
        // 订单发货
        else if (31 === intval($info['send_scene'])) {
            $info['otherContent'] = [$this->builtInArray[0], $this->builtInArray[12], $this->builtInArray[21], $this->builtInArray[22], $this->builtInArray[23]];
        }
        // 订单退款
        else if (32 === intval($info['send_scene'])) {
            $info['otherContent'] = [$this->builtInArray[8], $this->builtInArray[1], $this->builtInArray[0]];
        }
        // 充值成功
        else if (33 === intval($info['send_scene'])) {
            $info['otherContent'] = [$this->builtInArray[2], $this->builtInArray[4], $this->builtInArray[6], $this->builtInArray[13]];
        }
        // 积分变动
        else if (34 === intval($info['send_scene'])) {
            $info['otherContent'] = [$this->builtInArray[18], $this->builtInArray[9], $this->builtInArray[10], $this->builtInArray[14]];
        }
        // 余额变动
        else if (35 === intval($info['send_scene'])) {
            $info['otherContent'] = [$this->builtInArray[19], $this->builtInArray[5], $this->builtInArray[6], $this->builtInArray[14]];
        }
        // 订单付款
        else if (50 === intval($info['send_scene'])) {
            $info['otherContent'] = [$this->builtInArray[7], $this->builtInArray[1], $this->builtInArray[0]];
        }
        // 订单收货
        else if (51 === intval($info['send_scene'])) {
            $info['otherContent'] = [$this->builtInArray[29], $this->builtInArray[0], $this->builtInArray[11], $this->builtInArray[3], $this->builtInArray[27]];
        }
        // 订单维权
        else if (52 === intval($info['send_scene'])) {
            $info['otherContent'] = [$this->builtInArray[24], $this->builtInArray[25], $this->builtInArray[26], $this->builtInArray[1], $this->builtInArray[0]];
        }
        // 库存预警
        else if (53 === intval($info['send_scene'])) {
            $info['otherContent'] = [$this->builtInArray[30], $this->builtInArray[28], $this->builtInArray[17]];
        }

        return $info;
    }

    // 获取发送手机短信内容
    public function getSendMobileContent($users = [], $content = [], $sendScene = [])
    {

        // 如果商品已经推送过预警则跳转不再推送
        // if (!empty($content['goods_id']) && in_array(53, $sendScene)) {
        //     $result = $this->getNoticeSendContent(0, 3, $content['goods_id'], false);
        //     if (!empty($result)) return false;
        // }

        // 【应用】-【消息通知】-【接口配置】-【短信配置】
        $config = tpCache('sms');
        foreach ($config as $value) {
            if (empty($value)) return false;
        }

        // 是否传入用户信息、发送内容、发送类型，缺一则返回结束
        if (empty($users) || empty($content) || empty($sendScene)) return false;

        $where = [
            'sms_type' => intval($config['sms_type']),
            'send_scene' => ['IN', $sendScene]
        ];
        $mobileList = Db::name('sms_template')->where($where)->select();
        foreach ($mobileList as $key => $value) {
            // 如果关闭推送开关则跳过
            if (empty($value['is_open'])) {
                unset($value);
                unset($mobileList[$key]);
                continue;
            }

            // 买家通知
            if (in_array($value['send_scene'], [30, 31, 32, 33, 34, 35]) && !empty($users['mobile'])) {
                $value['mobile'] = trim($users['mobile']);
            }
            // 卖家通知
            else if (in_array($value['send_scene'], [50, 51, 52, 53]) && !empty($config['sms_test_mobile'])) {
                $value['mobile'] = trim($config['sms_test_mobile']);
            }

            // 如果没有推送手机号码则跳过
            if (empty($value['mobile'])) {
                unset($value);
                unset($mobileList[$key]);
                continue;
            }

            $mobileList[$key] = $value;
        }

        if (!empty($mobileList)) {
            $sendContent = [
                'mobile' => $mobileList,
                'content' => $content,
            ];
            $resultID = $this->addNoticeSendContent($sendContent, $content, 2, $sendScene);
            if (!empty($resultID)) return intval($resultID);
        }
        return false;
    }

    // 执行手机短信消息通知发送内容
    public function executeSendMobileContent($send_id = '', $return = true)
    {
        $noticeList = $this->getNoticeSendContent($send_id, 2);
        if (empty($noticeList)) $this->success('没有推送消息');

        $config = tpCache('sms');
        foreach ($noticeList as $noticeSend) {
            if (!empty($noticeSend['send_content']['mobile']) && !empty($noticeSend['send_content']['content'])) {
                // 推送内容
                $content = $noticeSend['send_content']['content'];
                $mobileList = $noticeSend['send_content']['mobile'];

                // 处理推送消息
                foreach ($mobileList as $value) {
                    if (!empty($value['is_open']) && !empty($content)) {
                        // 买家通知: 30, 31, 32, 33, 34, 35; 卖家通知: 50, 51, 52, 53
                        if (in_array($value['send_scene'], [30, 31, 32, 33, 34, 35, 50, 51, 52, 53]) && !empty($value['mobile'])) {
                            // if (34 === intval($value['send_scene'])) {
                                // 获取手机短信消息通知发送模板
                                $result = $this->getMobileTemplateContent($value, $content);
                                // dump($result);
                                // 执行手机短信消息通知接口
                                sendSms($value['send_scene'], $value['mobile'], $result, 0, $config);
                                // dump(2);
                                // exit;
                            // }
                        }
                    }
                }
            }
        }
        // dump(1);
        // exit;
        // 更新通知发送记录表信息
        $this->updateNoticeSendContent($send_id, 2);

        // 返回结束
        if (!empty($return)) $this->success('推送成功');
    }

    // 获取手机短信消息通知发送模板
    public function getMobileTemplateContent($value = [], $content = [])
    {
        // 加载手机短信模板值
        $this->shopName = tpCache('web.web_name');

        // 商城下单
        if (!empty($content['order_id'])) {
            // 积分变动推送---减少
            if (34 === intval($value['send_scene']) && !empty($content['order_points'])) {
                $this->changeScores = '-' . floatval($content['order_points']);
            }
            // 积分变动推送---增加
            else if (34 === intval($value['send_scene']) && !empty($content['obtain_scores'])) {
                $this->changeScores = '+' . floatval($content['obtain_scores']);
            }
            // 余额变动推送---减少
            else if (35 === intval($value['send_scene'])) {
                $this->changeMoney = '-' . floatval($content['order_amount']);
            }
        }
        // 余额充值---增加
        if (in_array($value['send_scene'], [33, 35]) && !empty($content['moneyid'])) {
            $this->changeMoney = '+' . floatval($content['money']);
        }

        // 查询客户当前余额
        if (in_array($value['send_scene'], [33, 34, 35]) && !empty($content['users_id'])) {
            $usersInfo = Db::name('users')->field('users_money, scores')->where(['users_id' => intval($content['users_id'])])->find();
            $this->usersMoney = !empty($usersInfo['users_money']) ? floatval($usersInfo['users_money']) : 0;
            $this->usersScores = !empty($usersInfo['scores']) ? intval($usersInfo['scores']) : 0;
        }

        if (!empty($content['order_code'])) $this->orderCode = $content['order_code'];
        if (!empty($content['actual_price'])) $this->actualPrice = floatval($content['actual_price']);
        if (!empty($content['pay_time'])) $this->pay_time = date('Y-m-d H:i:s', $content['pay_time']);
        if (!empty($content['express_time'])) $this->express_time = date('Y-m-d H:i:s', $content['express_time']);
        if (!empty($content['confirm_time'])) $this->confirm_time = date('Y-m-d H:i:s', $content['confirm_time']);

        // 商品标题处理
        $this->goodsTitle = !empty($content['goodsTitle']) ? $content['goodsTitle'] : '';
        if (empty($this->goodsTitle) && !empty($content['order_id'])) {
            $this->goodsTitle = Db::name('shop_order_details')->where(['order_id'=>$content['order_id']])->order('details_id desc')->getField('product_name');
        }
        if (!empty($this->goodsTitle)) {
            $this->goodsTitleNew = msubstr($this->goodsTitle, 0, 30);
            $str = trim($this->goodsTitle) === trim($this->goodsTitleNew) ? '' : '...';
            $this->goodsTitle = $this->goodsTitleNew . $str;
        }

        // 处理邮件模板值
        $result = $this->handleSmsTemplate($value, false);
        return $result;
    }

    // 处理短信模板内容
    public function handleSmsTemplate($info = [], $title = true)
    {
        if (!empty($title)) {
            // 标题处理
            $info['tpl_content_text'] = str_replace(['${money}','{1}'], $this->changeMoney, $info['tpl_content']);
            $info['tpl_content_text'] = str_replace(['${pay_time}','{1}'], $this->pay_time, $info['tpl_content_text']);
            $info['tpl_content_text'] = str_replace(['${shop_name}','{1}'], $this->shopName, $info['tpl_content_text']);
            $info['tpl_content_text'] = str_replace(['${users_money}','{1}'], $this->usersMoney, $info['tpl_content_text']);
            $info['tpl_content_text'] = str_replace(['${goods_title}','{1}'], $this->goodsTitle, $info['tpl_content_text']);
            $info['tpl_content_text'] = str_replace(['${score}','{1}'], $this->scores, $info['tpl_content_text']);
            $info['tpl_content_text'] = str_replace(['${scores}','{1}'], $this->scores, $info['tpl_content_text']);
            $info['tpl_content_text'] = str_replace(['${users_score}','{1}'], $this->scores, $info['tpl_content_text']);
            $info['tpl_content_text'] = str_replace(['${express_time}','{1}'], $this->express_time, $info['tpl_content_text']);
            $info['tpl_content_text'] = str_replace(['${confirm_time}','{1}'], $this->confirm_time, $info['tpl_content_text']);
            $info['tpl_content_text'] = str_replace(['${order_code}','{1}'], $this->orderCode, $info['tpl_content_text']);
            return $info;
        }
        else {
            // 其他附加内容处理
            $result = [];
            // 订单支付
            if (30 === intval($info['send_scene'])) {
                $result['goodsTitle'] = $this->goodsTitle;
            }
            // 订单发货
            else if (31 === intval($info['send_scene'])) {
                $result['goodsTitle'] = $this->goodsTitle;
                $result['expressTime'] = $this->express_time;
            }
            // 订单退款
            else if (32 === intval($info['send_scene'])) {
                $result['actualPrice'] = $this->actualPrice;
            }
            // 充值成功
            else if (33 === intval($info['send_scene'])) {
                $result['usersMoney'] = $this->usersMoney;
                $result['changeMoney'] = $this->changeMoney;
            }
            // 积分变动
            else if (34 === intval($info['send_scene'])) {
                $result['usersScores'] = $this->usersScores;
                $result['changeScores'] = $this->changeScores;
            }
            // 余额变动
            else if (35 === intval($info['send_scene'])) {
                $result['usersMoney'] = $this->usersMoney;
                $result['changeMoney'] = $this->changeMoney;
            }
            // 订单付款
            else if (50 === intval($info['send_scene'])) {
                $result['pay_time'] = $this->pay_time;
                $result['shop_name'] = $this->shopName;
                $result['goodsTitle'] = $this->goodsTitle;
            }
            // 订单收货
            else if (51 === intval($info['send_scene'])) {
                $result['orderCode'] = $this->orderCode;
                $result['confirmTime'] = $this->confirm_time;
            }
            // 订单维权
            else if (52 === intval($info['send_scene'])) {
                $result['orderCode'] = $this->orderCode;
            }
            // 库存预警
            else if (53 === intval($info['send_scene'])) {
                $result['goodsTitle'] = $this->goodsTitle;
            }
            return $result;
        }
    }

    // 设置内置内容数据
    private function setBuiltInArray()
    {
        // 当前时间戳
        $this->times = getTime();
        // 变动原因
        $this->changeReason = '充值成功';
        // 变动金额、积分
        $this->changeMoney = $this->changeScores = $this->actualPrice = '+99';
        // 账户金额
        $this->usersMoney = $this->usersScores = 1000;
        // 变动类型
        $this->changeType = '增加';
        // 操作金额
        $this->money = $this->scores = 99;
        // 库存预警时的剩余库存
        $this->goodsStock = 10;
        // 标题名称
        $this->nickname = '张三';
        // 售后类型
        $this->service_type = '售后维权申请';
        // 商城名称
        $this->shopName = '办公用品超市';
        // 标题名称
        $this->goodsTitle = '办公电脑桌';
        // 接收参数
        $this->paramArr = input('param.');
        // 快递信息
        $this->express_name = '顺丰快递';
        $this->express_order = 'SF0000001';
        $this->address = '海南省海口市A区A街道A小区';
        // 订单号
        $this->orderCode = date('Ymd') . $this->times . rand(10, 100);
        // 当前年月日时分秒
        $this->dates = $this->add_time = $this->pay_time = $this->express_time = $this->confirm_time = $this->service_time = date('Y-m-d H:i:s');
    }

    // 获取内置内容数组
    private function getBuiltInArray()
    {
        // 内置固定内容
        return [
            0 => '订单编号：' . $this->orderCode,
            1 => '商品名称：' . $this->goodsTitle,
            2 => '客户昵称：' . $this->nickname,
            3 => '支付金额：' . $this->money,
            4 => '充值金额：' . $this->money,
            5 => '变动金额：' . $this->changeMoney,
            6 => '账户金额：' . $this->usersMoney,
            7 => '付款金额：' . $this->money,
            8 => '退款总金额：' . $this->actualPrice,
            9 => '变动积分：' . $this->changeScores,
            10 => '账户积分：' . $this->usersScores,
            11 => '下单时间：' . $this->add_time,
            12 => '发货时间：' . $this->express_time,
            13 => '充值时间：' . $this->dates,
            14 => '变动时间：' . $this->dates,
            15 => '付款时间：' . $this->pay_time,
            16 => '操作时间：' . $this->dates,
            17 => '预警时间：' . $this->dates,
            18 => '变动原因：' . $this->changeReason,
            19 => '变动原因：' . $this->changeReason,
            20 => '充值方式：在线充值',
            21 => '物流公司：' . $this->express_name,
            22 => '快递单号：' . $this->express_order,
            23 => '收货地址：' . $this->address,
            24 => '售后类型：' . $this->service_type,
            25 => '申请时间：' . $this->service_time,
            26 => '商品金额：' . $this->money,
            27 => '备注：感谢您的使用',
            28 => '预警内容：' . $this->goodsTitle . '一库存不足',
            29 => '收件人：' . $this->nickname,
            30 => '预警库存：' . '剩余' . $this->goodsStock,
        ];
    }

    // 添加通知发送记录表信息
    private function addNoticeSendContent($sendContent = [], $content = [], $sendType = 1, $sendScene = [])
    {
        $insert = [
            'goods_id' => !empty($content['goods_id']) ? intval($content['goods_id']) : 0,
            'order_id' => !empty($content['order_id']) ? intval($content['order_id']) : 0,
            'service_id' => !empty($content['service_id']) ? intval($content['service_id']) : 0,
            'send_type' => intval($sendType),
            'send_scene' => implode(',', $sendScene),
            'send_status' => 0,
            'send_result' => '',
            'send_content' => json_encode($sendContent),
            'add_time' => $this->times,
            'update_time' => $this->times,
        ];
        return Db::name('notice_send')->insertGetId($insert);
    }

    // 获取通知发送记录表信息
    private function getNoticeSendContent($send_id = '', $send_type = 1, $goods_id = 0, $send_status = true)
    {
        $send_id = is_array($send_id) ? $send_id : explode(',', $send_id);
        $where = [
            // 'send_id' => intval($send_id),
            'send_id' => ['IN', $send_id],
            'send_type' => intval($send_type),
            'send_status' => 0,
        ];
        if (!empty($goods_id) && empty($send_status)) {
            unset($where['send_id']);
            unset($where['send_status']);
            $where['goods_id'] = intval($goods_id);
        }
        $result = Db::name('notice_send')->where($where)->select();
        if (!empty($result)) {
            foreach ($result as $key => $value) {
                $result[$key]['send_content'] = !empty($value['send_content']) ? json_decode($value['send_content'], true) : [];
            }
        }
        return $result;
    }

    // 更新通知发送记录表信息
    private function updateNoticeSendContent($send_id = '', $send_type = 1)
    {
        $send_id = is_array($send_id) ? $send_id : explode(',', $send_id);
        $where = [
            // 'send_id' => intval($send_id),
            'send_id' => ['IN', $send_id],
            'send_type' => intval($send_type),
            'send_status' => 0,
        ];
        $update = [
            'send_status' => 1,
            'update_time' => $this->times,
        ];
        Db::name('notice_send')->where($where)->update($update);
    }
}
